package com.yztctech.a25_03_bindservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import com.yztctech.a25_03_bindservice.base.MyBaseService;

public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {
    private LoadMediaService loadMediaService;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            loadMediaService = ((LoadMediaService.LoadMediaBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        initView();

    }

    private void initView() {
        findViewById(R.id.btn_bind).setOnClickListener(this);
        findViewById(R.id.btn_download).setOnClickListener(this);
        findViewById(R.id.btn_unbind).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_bind://绑定Service----->需要三个参数 前两个实例化 第三个直接使用
                Log.e("Tag", "MainActivity2-------------onClick:btn_bind");
                bindLoadMediaService();
                break;
            case R.id.btn_unbind://解除绑定
                Log.e("Tag", "MainActivity2-------------onClick:btn_unbind");
                unbindLoadMediaService();
                break;
            case R.id.btn_download://持有了service就可以控制里边的任意需求方法了
                Log.e("Tag", "MainActivity2-------------onClick:btn_download");
                doSomething();
                break;
        }
    }


    private void bindLoadMediaService() {
        Intent service = new Intent(this, LoadMediaService.class);
        bindService(service, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void doSomething() {
        loadMediaService.loadMedia("http://www.wwww2");
    }

    private void unbindLoadMediaService() {
        unbindService(serviceConnection);
    }


}